package com.xytc.company.company_backend.adminEndPoint.controller;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xytc.company.company_backend.adminEndPoint.entity.dao.FoodRepositoryDao;
import com.xytc.company.company_backend.adminEndPoint.entity.rto.FoodRto;
import com.xytc.company.company_backend.adminEndPoint.mapper.IFoodManageMapper;
import com.xytc.company.company_backend.adminEndPoint.service.FoodManageServiceImpl;
import com.xytc.company.company_backend.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/company/foodManage")
public class FoodManageController {

    @Autowired
    private IFoodManageMapper foodManageMapper;

    @Autowired
    private FoodManageServiceImpl foodManageService;

    /**
     * 接口2.1 新增或编辑菜品信息
     *
     * @param foodRTO
     * @return
     */
    @PostMapping("/addOrUpdateFood")
    public Result<?> addOrUpdateStore(@RequestBody FoodRto foodRTO) {

        FoodRepositoryDao foodRepositoryDao = new FoodRepositoryDao();

        foodRepositoryDao.setFoodName(foodRTO.getFoodName());
        foodRepositoryDao.setStoreId(foodRTO.getStoreId());
        foodRepositoryDao.setStorePrice(foodRTO.getStorePrice());
        foodRepositoryDao.setDescription(foodRTO.getDescription());
        foodRepositoryDao.setFoodStatus(1); // 新增菜品信息时，菜品状态为默认值 1；编辑接口不涉及菜品上架/下架 状态的更改，上架/下架由接口 2.3 来实现
        foodRepositoryDao.setDelFlag(0); // del_flag 标记为0；删除店铺由接口1.4 来实现
        if (StringUtils.isBlank(foodRTO.getId())) {
            // 新增菜品，先判断表中是否已经有同名的菜品，不允许添加重复店铺名称的店铺
            List<FoodRepositoryDao> list = foodManageMapper.selectList(
                    new LambdaQueryWrapper<FoodRepositoryDao>()
                            .eq(FoodRepositoryDao::getStoreId, foodRTO.getStoreId()).
                            eq(FoodRepositoryDao::getFoodName, foodRTO.getFoodName())
                            .eq(FoodRepositoryDao::getDelFlag, 0));
            if (list != null && !list.isEmpty()) {
                return Result.error("店铺【" + foodRTO.getStoreId() + "】，菜品【" + foodRTO.getFoodName() + "】已存在，同一个店铺不能录入重复名称的菜品");
            }
            foodRepositoryDao.setCreateTime(new Date()); // 新增店铺时，创建时间为接口调用时间
            // 将新增菜品的图片，逐一从临时目录移动到正式目录，并生成
            JSONArray imageFinalUrls = new JSONArray();
            String partDir = foodRTO.getStoreId() + File.separator + "foods" + File.separator;
            foodRTO.getImages().toJavaList(String.class).forEach(tempPath -> {
                String imageFinalUrl = foodManageService.moveTemp2FinalDirAndBuildFinalUrl(tempPath, partDir);
                imageFinalUrls.add(imageFinalUrl);
            });
            foodRepositoryDao.setImages(imageFinalUrls.toJSONString());
            foodRepositoryDao.setCreateTime(new Date()); // 新增店铺时，创建时间为接口调用时间
            // 菜品id为null或空字符串，新增菜品
            foodManageMapper.insert(foodRepositoryDao);
        } else {
            foodRepositoryDao.setId(foodRTO.getId());
            // 更新菜品信息
            foodRepositoryDao.setId(foodRTO.getId());
            // 如果涉及到图片更新，则为新上传的图片生成url，并更新到 db中
            foodManageService.updateImagesAndUpdateUrls(foodRTO);
            foodRepositoryDao.setImages(foodRTO.getImages().toJSONString());
            // 菜品id不为null，也不为空字符串，更新菜品
            foodManageMapper.updateById(foodRepositoryDao);
        }

        return Result.ok();
    }


    /**
     * 接口2.2 根据菜品名或店铺名查询符合条件的菜品
     *
     * @param keyword  为null或空字符串，这sql语句中，like "%%"，即不设置过滤条件
     * @param pageNo
     * @param pageSize
     * @return
     */
    @GetMapping("/queryFoodByKeyword")
    public Result<?> queryFoodByKeyword(@RequestParam("keyword") String keyword,
                                        @RequestParam(value = "pageNo", required = false, defaultValue = "1") Integer pageNo,
                                        @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize) {
        // 当前端传递null时，将其设置为空字符串，这样 拼接sql时，不会出错
        if (keyword == null) {
            keyword = "%";
        }
        Integer totalCount = foodManageMapper.queryFoodsWithStoreInfosCount(keyword);
        int totalPages = 0;
        List<HashMap<String, Object>> pageFoods;
        if (totalCount > 0) {
            Integer limit = (pageNo - 1) * pageSize;
            pageFoods = foodManageMapper.queryFoodsWithStoreInfos(keyword, limit, pageSize);
        } else {
            pageFoods = new ArrayList<>();
        }

        pageFoods.forEach(foodInfoMap -> {
            String imageString = (String) foodInfoMap.get("images");
            foodInfoMap.put("images", JSONArray.parseArray(imageString));
        });

        JSONObject resultData = new JSONObject();
        resultData.put("totalPages", totalPages);
        resultData.put("totalCount", totalCount);
        resultData.put("currentPage", pageNo);
        resultData.put("foods", pageFoods);

        return Result.ok(resultData);
    }

    /**
     * 接口2.3 切换菜品状态
     *
     * @param foodId
     * @param status 1 表示上架中；2 表示下架
     * @return
     */
    @PutMapping("/changeFoodState")
    public Result<?> changeFoodState(@RequestParam("foodId") String foodId, @RequestParam("status") Integer status) {

        FoodRepositoryDao foodRepositoryDao = new FoodRepositoryDao();
        foodRepositoryDao.setId(foodId);
        foodRepositoryDao.setFoodStatus(status);

        try {
            foodManageMapper.updateById(foodRepositoryDao);
            log.info("菜品{}状态更新成功，成功更新为 {}", foodId, status);
            return Result.ok("菜品状态更新成功");
        } catch (Exception ex) {
            log.error("切换菜品状态失败 {}", ex);
            return Result.error(500, "菜品状态更新成功");
        }
    }

    /**
     * 接口2.4 删除菜品
     *
     * @param foodId
     * @return
     */
    @DeleteMapping("/deleteFood")
    public Result<?> deleteFood(@RequestParam("foodId") String foodId) {

        FoodRepositoryDao foodRepositoryDao = new FoodRepositoryDao();
        foodRepositoryDao.setId(foodId);
        foodRepositoryDao.setDelFlag(1);
        try {
            foodManageMapper.updateById(foodRepositoryDao);
            log.info("菜品{}删除成功", foodId);
            return Result.ok("菜品删除成功");
        } catch (Exception ex) {
            log.error("菜品删除失败 {}", ex);
            return Result.error(500, "菜品删除失败");
        }
    }
}
